﻿using System;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace InfoPathExtractionRules
{
    public class ExtractSolutionId : ExtractionRule
    {
        private readonly static string canaryStart = IPExtractionUtil.CanaryStart;
        /// <summary>
        /// InfoPath Server sets a cookie for the first canary when opening a form in the browser
        /// The name of that cookie follows the format: _InfoPath_CanaryValue%SolutionId%
        /// We are trying to extract the %SolutionId% value
        /// This value is required for subsequent postbacks to the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Extract(object sender, ExtractionEventArgs e)
        {
            foreach (System.Net.Cookie cookie in e.Response.Cookies)
            {
                if (cookie.Name.StartsWith(canaryStart))
                {
                    string solutionId = cookie.Name.Substring(canaryStart.Length);

                    e.Success = true;
                    if (string.IsNullOrEmpty(solutionId))
                    {
                        e.Success = false;
                        e.Message = "Could not find solutionId";
                        return;
                    }

                    e.WebTest.Context[this.ContextParameterName] = solutionId;

                    return;
                }
            }

            e.Success = false;
            e.Message = "Could not find solutionId";
        }

        public override string RuleName
        {
            get { return "ExtractSolutionId"; }
        }
    }
}
